package org.itboys.mobile.service.mongo.front;

import org.apache.commons.lang.StringUtils;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.image.ImageUtils;
import org.itboys.commons.utils.reg.IdCardUtils;
import org.itboys.commons.utils.reg.RegUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.score.SundayScoreConfigMapper;
import org.itboys.mobile.dto.SundayMemberDto;
import org.itboys.mobile.dto.SundayMemberSessionDto;
import org.itboys.mobile.dto.product.SundayProductDto;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.order.SundayOrder;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.entity.mysql.score.SundayScoreConfig;
import org.itboys.mobile.entity.mysql.wallet.SundayWallet;
import org.itboys.mobile.service.mysql.front.SundayFrontCouponService;
import org.itboys.mobile.service.mysql.front.SundayFrontWalletService;
import org.itboys.mobile.service.mysql.web.order.SundayOrderService;
import org.itboys.mobile.service.mysql.web.score.SundayScoreConfigService;
import org.itboys.mobile.util.NameUtil;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.ParamUtil;
import org.itboys.weixin.tools.WeixinUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by zhangyang on 2018/1/4.
 * 圣代_用户_service_mobile
 */
@Service
public class SundayFrontMemberService extends BaseMongoService<SundayMember>{
    @Autowired
    private SundayFrontCodeService codeService;
    @Autowired
    private SundayFrontCidService cidService;
    @Autowired
    private SundayOrderService orderService;
    @Autowired
    private SundayFrontCouponService couponService;
    @Autowired
    private SundayFrontCollectionService collectionService;
    @Autowired
    private SundayFrontFootprintService footprintService;
    @Autowired
    private SundayFrontWalletService walletService;
    @Autowired
    private SundayScoreConfigMapper scoreConfigMapper;
    @Autowired
    private ResourceHolder resourceHolder;


    @Resource(name = "mobileDs")
    private MongoDataSource sundayDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return sundayDataSource;
    }

    @Override
    protected Class<SundayMember> getEntityClass() {
        return SundayMember.class;
    }


    /*******************微信相关-开始******************************/
    /**
     * 处理来至微信的用户信息。使用openId判断标识
     * @param unionId
     * @param openId
     * @param nickName
     * @param wxLogo
     */
    public SundayMemberSessionDto handleMemberInfo(String unionId,
                                                   String openId,
                                                   String nickName,
                                                   String wxLogo,
                                                   long tjId, long projectId){
        SundayMember member=null;
        Map<String,Object> param=new HashMap<String ,Object>();
       param.put("isDeleted", SundayCommonConstants.NO);
        //使用openId标识用户(公众号)，使用unionId标识用户（服务号,需要绑定微信开放平台）
        param.put("weixinUnionId",unionId);
       // param.put("weixinOpenId",openId);
        List<SundayMember> oldMembers=super.list(param);
        if(ListUtil.isNotNull(oldMembers)){
            member=oldMembers.get(0);

        }else {
            member=initMember(nickName,null,wxLogo,SundayCommonConstants.third_type_weixin,unionId,openId,tjId);
         /*   member.setNickName(nickName);
            member.setPassword(Digests.md5(NameUtil.getRandomPassWord()));
            member.setWeixinUnionId(unionId);
            member.setWeixinOpenId(openId);
            //保存微信头像
            String random= NumberUtil.generateNumber("AG");
            String savePath = resourceHolder.getStringValue("fileUploadPath")+"/wxlogo/"+random+".jpg";
            ImageUtils.buildImg(savePath,wxLogo);
            //头像半链接
            member.setImage("/wxlogo/"+random+".jpg");
            //初始化个人信息
            member.setUserType(SundayCommonConstants.user_type_member);
            // 0欠费或冻结，1正常（默认）
            member.setStatus(SundayCommonConstants.NO);
            //推荐人相关
            if(LongUtil.isNotZreo(tjId)){
                SundayMember tj=super.getById(tjId);
                member.setFirstTjId(tj.getId());
                member.setSecondTjId(tj.getFirstTjId());
            }else{
                member.setFirstTjId(0l);
                member.setSecondTjId(0l);
            }
            super.save(member);
            //用户创建后的其他操作
            couponService.sendCoupon(member.getId(),SundayCommonConstants.PROMOTION_COUPON_TYPE_SYSTEM);
            //创建钱包
            walletService.insert(new SundayWallet(member.getId()));*/
        }
        SundayMemberSessionDto memberDto=new SundayMemberSessionDto(member.getId(),  member.getWeixinUnionId(),member.getWeixinOpenId());
        return memberDto;
    }

    /**
     * 通过weixinOpenId判断用户是否存在
     * @param openId
     * @return
     */
    public SundayMemberSessionDto checkOpenId(String openId){
        Map<String,Object> param=new HashMap<String ,Object>();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("weixinOpenId",openId);
        List<SundayMember> members = super.list(param);
        if(ListUtil.isNull(members)){
            return null;
        };
        SundayMember member = members.get(0);
        return new SundayMemberSessionDto(member.getId(),  member.getWeixinUnionId(),member.getWeixinOpenId());
    }
    /**
     * 将用户转换DTO保存到sesssion中。微信专用
     * @param request
     * @param memberId
     * @param memberSessionDto
     */
    public SundayMemberSessionDto insertMemberToSession(HttpServletRequest request, Long memberId, SundayMemberSessionDto memberSessionDto){
        SundayMember member = null;
        if(LongUtil.isNotNull(memberId)){
            member=super.getById(memberId);
            memberSessionDto=new SundayMemberSessionDto(member.getId(),  member.getWeixinUnionId(),member.getWeixinOpenId());
        }
        //logger.info("-----------插入session中的用户信息,openID==="+memberSessionDto.getWeixinOpenId());
        //先情况
        request.getSession().removeAttribute("member");
        request.getSession().setAttribute("member", memberSessionDto);
        return memberSessionDto;
    }

    /**
     * 清除用户session
     * @param request
     * @param memberId
     */
    public void clearMemberToSession(HttpServletRequest request, Long memberId){
        request.getSession().setAttribute("member", null);
    }

    /*******************微信相关-结束******************************/

    /******************************爱购特殊登陆相关******************/
    /**
     * 验证码登录
     * @param mobile    手机号
     * @param code  验证码
     * @return  dto
     */
    public SundayMemberDto loginWithCode(String mobile, String code){
        //校验验证码。
        int check_code=codeService.checkCode(mobile,code, SundayCommonConstants.validate_code_type_code_login);
        if(check_code!=0){
            throw new ErrorException("验证码错误。");
        }
        Map<String, Object> param =new HashMap<String,Object>();
        //查找用户
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("mobile", mobile);
        param.put("userType",SundayCommonConstants.user_type_member);
        List<SundayMember> members = super.list(param);
        SundayMemberDto memberDto = null;
        //没有注册过用户则创建一个
        if(ListUtil.isNull(members)){
            SundayMember member = initMember(null,mobile, null,null,null,null,0l);
            memberDto = packageDtoSingle(member,0l,false,true);
        }else{
            SundayMember member = members.get(0);
            if (member.getStatus()!=SundayCommonConstants.user_status_normal) {
                throw new ErrorException("账户被冻结");
            }
            memberDto = packageDtoSingle(member,0l,false,true);
        }
        return memberDto;
    }


    /**
     * 退出登录。删除CID
     * @param memberId
     */
    public void logout(long memberId){
        cidService.clear(memberId);
    }

    /**
     * 修改个人信息
     * @param memberId  用户id
     * @param  nickName 昵称
     * @param mobileName    联系电话
     * @param address   地址
     * @param email     邮箱
     * @param image     头像
     * @param idCard    身份证号
     * @param desc      个人简介
     * @param birthDate 生日
     * @param sex        性别
     */
    public SundayMemberDto update(Long memberId,String nickName,String mobileName,String address,String email,
                                  String image,String idCard, String desc,String birthDate,Integer sex){
        if(StringUtils.isNotEmpty(email)&&!RegUtils.isEmail(email)){
            throw new ErrorException("请输入正确的邮箱");
        }
        if(StringUtils.isNotEmpty(idCard)&&!IdCardUtils.isCard(idCard)){
            throw new ErrorException(("请输入正确的身份证号"));
        }
        SundayMember member =new SundayMember();
        member.setId(memberId);
        member.setNickName(nickName);
        member.setMobileName(mobileName);
        member.setAddress(address);
        member.setEmail(email);
        member.setImage(image);
        member.setIdCard(idCard);
        member.setDesc(desc);
        member.setBirthDate(birthDate);
        member.setSex(sex);
        super.updateExceptEmpty(memberId,member);

        return packageDtoSingle(null,memberId,false,true);
    }

    /**
     * 组装用户DTO
     * @param member
     * @param memberId
     * @param isWallet 是否组装钱包，等级信息
     * @param isCenterInfo，是否组装用户中心的信息（订单，收藏，优惠券）
     * @return
     */
    public SundayMemberDto packageDtoSingle(SundayMember member,Long memberId,boolean isWallet,boolean isCenterInfo) {
        String imgRoot = resourceHolder.getStringValue("imgRoot");
        SundayMemberDto memberDto =new SundayMemberDto();
        //2018年1月19日新增
        if(member==null)member=super.getById(memberId);
        memberDto.setId(member.getId());
        memberDto.setCreateDate(member.getCreateDate());
        memberDto.setCreateTime(member.getCreateTime());
        memberDto.setNickName(member.getNickName());
        memberDto.setEmail(member.getEmail());
        memberDto.setImage(imgRoot+member.getImage());
        memberDto.setMobile(member.getMobile());
        memberDto.setIdCard(member.getIdCard());
        memberDto.setBirthDate(member.getBirthDate());
        memberDto.setSex(member.getSex());
        memberDto.setDesc(member.getDesc());
        memberDto.setIsGold(member.getIsGold());

        //组装用户等级、权限、钱包信息
        if(isWallet){
            SundayWallet wallet= walletService.getByMemberId(member.getId());
            SundayScoreConfig scoreConfig = null;
            List<SundayScoreConfig> scoreConfigs = scoreConfigMapper.select(null);
            //根据积分获取等级
            for(SundayScoreConfig sc:scoreConfigs){
                if(wallet.getIntegral().compareTo(sc.getLine())==1){
                   // logger.info("--------");
                    scoreConfig=sc;
                }
            }
            memberDto.setGrade(scoreConfig.getName());
            memberDto.setIsAg(scoreConfig.getIsAg());
            memberDto.setIsTry(scoreConfig.getIsTry());
            memberDto.setTotalAmount(wallet.getTotalAmount());
            memberDto.setIntegral(wallet.getIntegral());
            memberDto.setAigouCoin(wallet.getAigouCoin());
            //2018年3月5日，用户贝壳余额
            memberDto.setConch(wallet.getConch());

            memberDto.setChargeDiscountAgCoin(scoreConfig.getChargeDiscountAgCoin());
            memberDto.setChangeAmountAgCoin(scoreConfig.getChangeAmountAgCoin());
            memberDto.setDiscount(scoreConfig.getDiscount());
            //用户获取积分的配置信息
            memberDto.setBuyScore(scoreConfig.getBuyScore());
            memberDto.setCommentScore(scoreConfig.getCommentScore());
            memberDto.setCommunityScore(scoreConfig.getCommunityScore());
            memberDto.setShareScore(scoreConfig.getShareScore());
            //用户获取爱购币的配置信息
            memberDto.setBuyAgCoin(scoreConfig.getBuyAgCoin());
            memberDto.setCommentAgCoin(scoreConfig.getCommentAgCoin());
            memberDto.setCommunityAgCoin(scoreConfig.getCommunityAgCoin());
            memberDto.setShareAgCoin(scoreConfig.getShareAgCoin());
        }
        //用户中心，订单，收藏等数量信息
        if(isCenterInfo){

            Map<String,Object> param = new HashMap<String,Object>();
            param.put("memberId",member.getId());
            param.put("isDeleted",SundayCommonConstants.NO);

            List<Integer> orderStatusList = new ArrayList<Integer>();
            orderStatusList.add(SundayCommonConstants.ORDER_STATUS_DFK);
            orderStatusList.add(SundayCommonConstants.ORDER_STATUS_DFH);
            orderStatusList.add(SundayCommonConstants.ORDER_STATUS_PSZ);
            orderStatusList.add(SundayCommonConstants.ORDER_STATUS_YSH);
            param.put("orderStatus in",orderStatusList);
            //2018年3月5日，排除拼团订单
            //2018年4月25日，
           /* List<Integer> types = new ArrayList<>();
            types.add(SundayCommonConstants.type_shiyong);
            param.put("type_not_in",types);*/
            List<SundayOrder> orderList = orderService.select(param);

            Long pendingPaymentCount = 0L;//待付款数量
            Long pendingGroupsCount = 0L;//待拼团数量
            Long pendingDeliveryCount = 0L;//待发货数量
            Long pendingCollectCount = 0L;//待收货数量
            Long pendingEvaluateCount = 0L;//待评价数量
            //订单售后数量
            Long afterCount = 0L;
            for(SundayOrder order : orderList){
                //不含试用订单
                if(order.getType()!=SundayCommonConstants.type_shiyong){
                    if(order.getStatus() == SundayCommonConstants.ORDER_STATUS_DFK){
                        pendingPaymentCount++;
                    }else if(order.getStatus() == SundayCommonConstants.ORDER_STATUS_DFH){
                        pendingDeliveryCount++;
                    }else if(order.getStatus() == SundayCommonConstants.ORDER_STATUS_PSZ){
                        pendingCollectCount++;
                    }else if(order.getStatus() == SundayCommonConstants.ORDER_STATUS_YSH){
                        pendingEvaluateCount++;
                    }
                }
                //含试用订单
                if(order.getStatus()==SundayCommonConstants.ORDER_STATUS_DTK||
                        order.getStatus()==SundayCommonConstants.ORDER_STATUS_DTH){
                    afterCount++;
                }
            }

            //优惠券数量
            param.clear();
            param.put("memberId",member.getId());
            //param.put("isDeleted",SundayCommonConstants.NO);
            param.put("status",SundayCommonConstants.coupon_status_wsy);
            Long couponCount = couponService.count(param);
            //收藏数量
            param.clear();
            param.put("memberId",member.getId());
            param.put("isDeleted",SundayCommonConstants.NO);
            param.put("type",SundayCommonConstants.collection_type_product);
            Long collectionCount = collectionService.count(param);



            //关注数量
            param.clear();
            param.put("memberId",member.getId());
            param.put("isDeleted",SundayCommonConstants.NO);
            param.put("type",SundayCommonConstants.collection_type_member);
            Long followCount = collectionService.count(param);

            //足迹数量
            param.clear();
            param.put("memberId",member.getId());
            param.put("isDeleted",SundayCommonConstants.NO);
            Long footprintCount = footprintService.count(param);
            memberDto.setPendingPaymentCount(pendingPaymentCount);
            memberDto.setPendingGroupsCount(pendingGroupsCount);
            memberDto.setPendingDeliveryCount(pendingDeliveryCount);
            memberDto.setPendingCollectCount(pendingCollectCount);
            memberDto.setPendingEvaluateCount(pendingEvaluateCount);
            memberDto.setCouponCount(couponCount);
            memberDto.setCollectionCount(collectionCount);
            memberDto.setAfterCount(afterCount);
            memberDto.setFollowCount(followCount);
            memberDto.setFootprintCount(footprintCount);
        }



        return  memberDto;
    }




    /**
     * 登陆或注册。使用验证码登录
     * @param mobile
     * @param code
     * @return
     */
    public SundayMemberDto login(String mobile,String code) {

        //检验验证码
        int result_code =codeService.checkCode(mobile,code,SundayCommonConstants.validate_code_type_code_login);
        if(result_code!=0){
            throw new ErrorException("验证码错误");
        }
        //校验用户
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",0);
        param.put("mobile",mobile);
        param.put("userType",SundayCommonConstants.user_type_member);
        List<SundayMember> oldMembers = super.list(param);
        SundayMember member = null;
        if(ListUtil.isNull(oldMembers)){
            //新建用户
            member=initMember(null,mobile, null,null,null,null,0l);
        }else{
            member=oldMembers.get(0);
        }
        SundayMemberDto memberDto=packageDtoSingle(member,0l,false,true);
        return memberDto;
    }

    /**
     * 登陆或注册。使用第三方 ,例如微信
     * @param nickName
     * @param image
     * @param thirdType
     * @param thirdUnionId
     * @param thirdOpenId
     * @return
     */
    public SundayMemberDto loginWithThird(String nickName,String image,Integer thirdType,String thirdUnionId,String thirdOpenId) {
        //校验用户
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",0);
        param.put("userType",SundayCommonConstants.user_type_member);
        //微信
       /* if(thirdType==SundayCommonConstants.third_type_weixin){
            param.put("weixinOpenId",thirdOpenId);
        }*/
        //微信，2018年5月3日，用uinoiId判断
        if(thirdType==SundayCommonConstants.third_type_weixin){
            param.put("weixinUnionId",thirdUnionId);
        }
        List<SundayMember> oldMembers = super.list(param);
        SundayMember member = null;
        if(ListUtil.isNull(oldMembers)){
            //新建用户
            member=initMember(nickName,null, image,thirdType,thirdUnionId,thirdOpenId,0l);
        }else{
            member=oldMembers.get(0);
        }
        SundayMemberDto memberDto=packageDtoSingle(member,0l,false,true);
        return memberDto;
    }
    /**
     * 初始化用户
     * @param nickName
     * @param mobile
     * @param image
     * @param thirdType
     * @param thirdUnionId
     * @param thirdOpenId
     * @param tjId 推荐人ID
     * @return
     */
    public SundayMember initMember(String nickName,String mobile,String image,Integer thirdType,String thirdUnionId,String thirdOpenId,Long tjId){
        SundayMember member = new SundayMember();
        member.setUserName(NumberUtil.generateNumber("APP"));
        if(StringUtils.isNotEmpty(nickName)){
            member.setNickName(nickName);
        }else{
            member.setNickName(NameUtil.getRandomName());
        }
        if(StringUtils.isNotEmpty(image)){
            String random=String.valueOf(new Date().getTime());
            //如果当前项目的上传文件目录下没有logo文件夹，请自行创建。此文件夹存放的是默认的头像和第三方登陆用户头像
            String savePath = resourceHolder.getStringValue("fileUploadPath")+"/logo/"+random+".jpg";
            ImageUtils.buildImg(savePath,image);
            member.setImage("/logo/"+random+".jpg");
        }else{
            member.setImage(NameUtil.getRandomLogo());
        }
        member.setMobile(mobile);
        member.setUserType(SundayCommonConstants.user_type_member);
        member.setPassword(Digests.md5(NameUtil.getRandomPassWord()));
        member.setStatus(SundayCommonConstants.user_status_normal);
        //第三方登陆相关
        if(thirdType!=null){
            if(thirdType==SundayCommonConstants.third_type_weixin){
                member.setWeixinUnionId(thirdUnionId);
                member.setWeixinOpenId(thirdOpenId);
            }else if(thirdType==SundayCommonConstants.third_type_qq){
                member.setQqUnionId(thirdUnionId);
            }else if(thirdType==SundayCommonConstants.third_type_weibo){
                member.setWeiboUnionId(thirdUnionId);
            }
        }
        //推荐人相关
        if(LongUtil.isNotZreo(tjId)){
            SundayMember tj=super.getById(tjId);
            member.setFirstTjId(tj.getId());
            member.setSecondTjId(tj.getFirstTjId());
        }else{
            member.setFirstTjId(0l);
            member.setSecondTjId(0l);
        }

        super.save(member);
        //用户创建后的其他操作
        couponService.sendCoupon(member.getId(),SundayCommonConstants.PROMOTION_COUPON_TYPE_SYSTEM);
        //创建钱包
        walletService.insert(new SundayWallet(member.getId()));
        return member;
    }

    /**
     * 分享页
     * @param memberId
     * @return
     */
    public SundayMember share(Long memberId) {
        SundayMember member = super.getById(memberId);
        //获取微信二维码
        if (StringUtils.isEmpty(member.getEwm())) {
            //  WeixinConfig weixinConfig = weixinConfigService.getById(1L);
            String appId = "wx24908878463e87bf";
            String secret = "b781b0cdb09beff0d47ff7ba6106f6dd";
            String access_token = WeixinUtils.getAccessToken(appId, secret);//发送请求  获取access_token
            String ticket = WeixinUtils.getTicket(access_token, "QR_LIMIT_SCENE", memberId);//获取生成带参数二维码用的ticket
            String random = String.valueOf(new Date().getTime());
            //微信二维码存放地址
            String memberEwmUrl = resourceHolder.getStringValue("fileUploadPath") + "/logo/" + random + ".png";
            String weixinEwmUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
            //将微信服务器上的二维码保存到自己的服务器上
            ImageUtils.buildImg(memberEwmUrl, weixinEwmUrl);
            member.setEwm("/logo/" + random + ".png");
            super.updateExceptEmpty(memberId,member);
        }
        member.setImage(resourceHolder.getStringValue("imgRoot") + member.getImage());
        member.setEwm(resourceHolder.getStringValue("imgRoot") + member.getEwm());
        return member;
    }

    /**
     * 获取我收藏（关注的用户）
     * @param request
     * @param memberId
     * @return
     */
    public List<SundayMemberDto> getCollection(HttpServletRequest request, Long memberId){
        List<Long> memberIds = collectionService.selectCollection(memberId,SundayCommonConstants.collection_type_member);
        Map<String,Object> param = ParamUtil.packageMongoExactParam(request, "nickName");
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("userType",SundayCommonConstants.user_type_member);
        param.put("id in",memberIds);

        String imgRoot = resourceHolder.getStringValue("imgRoot");
        List<SundayMember> members = super.pageQuery(request, param).getData();
        List<SundayMemberDto> dtos = new ArrayList<SundayMemberDto>();
        for(SundayMember member : members){
            SundayMemberDto dto = new SundayMemberDto();
            dto.setId(member.getId());
            dto.setImage(imgRoot+member.getImage());
            dto.setNickName(member.getNickName());
            dto.setCreateTime(member.getCreateTime());
            dtos.add(dto);
        }
        return dtos;
    }
    /**
     * 获取我的会员数据
     * @param memberId
     * @param type
     * @return
     */
   /* public List<SundayMemberDto> getLeaguerData(HttpServletRequest request,Long memberId,Integer type){
        Map<String,Object> param = ParamUtil.packageMongoExactParam(request, "");
        param.put("userType",SundayCommonConstants.user_type_member);
        if(type ==1){//获取一级会员数据
            param.put("firstTjId",memberId);
        }else{//获取二级会员数据
            param.put("secondTjId",memberId);
        }

        String imgRoot = resourceHolder.getStringValue("imgRoot");
        List<SundayMember> memberList = super.pageQuery(request, param).getData();
        List<SundayMemberDto> memberDtoList = new ArrayList<SundayMemberDto>();
        for(SundayMember member : memberList){
            SundayMemberDto dto = new SundayMemberDto();
            dto.setId(member.getId());
            dto.setImage(imgRoot+member.getImage());
            dto.setNickName(member.getNickName());
            dto.setCreateTime(member.getCreateTime());
            memberDtoList.add(dto);
        }
        return memberDtoList;
    }*/

    /**
     * 获取我的会员（一级会员和二级会员及统计总数）
     * @param memberId
     * @return
     */
    public Map<String,Object> getLeaguer(Long memberId){
        Map<String,Object> result = new HashMap<String,Object>();
        int firstTjTotal = 0;
        int secondTjTotal = 0;
        List<SundayMember> members= new ArrayList<>();
        List<SundayMemberDto> firstTjMembers = new ArrayList<>();
        List<SundayMemberDto> secondTjMembers = new ArrayList<>();
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("userType",SundayCommonConstants.user_type_member);
        param.put("firstTjId",memberId);
        members.addAll(super.list(param));
        param.clear();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("userType",SundayCommonConstants.user_type_member);
        param.put("secondTjId",memberId);
        members.addAll(super.list(param));



        String imgRoot = resourceHolder.getStringValue("imgRoot");


        for(SundayMember member : members){
            SundayMemberDto dto = new SundayMemberDto();
            dto.setId(member.getId());
            dto.setImage(imgRoot+member.getImage());
            dto.setNickName(member.getNickName());
            dto.setCreateTime(member.getCreateTime());
            if(LongUtil.isNotZreo(member.getFirstTjId())&&
                    member.getFirstTjId().longValue()==memberId.longValue()){
                firstTjMembers.add(dto);
                firstTjTotal++;
            }else if(LongUtil.isNotZreo(member.getSecondTjId())&&
                    member.getSecondTjId().longValue()==memberId.longValue()){
                secondTjMembers.add(dto);
                secondTjTotal++;
            }

        }
        result.put("firstTjTotal",firstTjTotal);
        result.put("secondTjTotal",secondTjTotal);
        result.put("firstTjMembers",firstTjMembers);
        result.put("secondTjMembers",secondTjMembers);

        return result;
    }

    /**
     * 是否绑定微信
     * @param memberId
     * @return
     */
    public Integer checkIsSign(Long memberId){
        SundayMember member = super.getById(memberId);
        if(StringUtils.isNotEmpty(member.getWeixinOpenId())){
            return 1;
        }else{
            return 0;
        }
    }
    /**
     * 重新绑定微信
     * @param memberId
     * @param nickName
     * @param image
     * @param thirdUnionId
     * @param thirdOpenId
     * @return
     */
    public void resign(Long memberId,String nickName,String image,String thirdUnionId,String thirdOpenId){
        SundayMember member = new SundayMember();
        member.setId(memberId);
        if(StringUtils.isNotEmpty(nickName)){
            member.setNickName(nickName);
        }
        if(StringUtils.isNotEmpty(image)){
            String random=String.valueOf(new Date().getTime());
            //如果当前项目的上传文件目录下没有logo文件夹，请自行创建。此文件夹存放的是默认的头像和第三方登陆用户头像
            String savePath = resourceHolder.getStringValue("fileUploadPath")+"/logo/"+random+".jpg";
            ImageUtils.buildImg(savePath,image);
            member.setImage("/logo/"+random+".jpg");
        }
        //第三方登陆相关
        member.setWeixinUnionId(thirdUnionId);
        member.setWeixinOpenId(thirdOpenId);
        super.updateExceptEmpty(memberId,member);
    }
}
